package com.jiuyin.dianjing.ui.activity.search;

import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;

import com.jiuyin.dianjing.R;
import com.jiuyin.dianjing.db.util.helper.SearchHistoryProviderHelper;
import com.jiuyin.dianjing.enums.SearchFragment;
import com.jiuyin.dianjing.event.GameInfoResultMsgEvent;
import com.jiuyin.dianjing.event.MsgDispatcher;
import com.jiuyin.dianjing.event.WordMsgEvent;
import com.jiuyin.dianjing.model.SearchHistoryModel;
import com.jiuyin.dianjing.ui.activity.base.BaseActivity;
import com.jiuyin.dianjing.util.IMEUtil;
import com.jiuyin.dianjing.util.LogUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_SEARCH;
import static com.jiuyin.dianjing.api.constant.ApiConstant.KEY_TYPE;
import static com.jiuyin.dianjing.app.HelperApplication.getContext;
import static com.jiuyin.dianjing.constant.HelperConstant.EXTRA_KEY_SEARCH_SUGGEST;

/**
 * 游戏资讯搜索页面
 */
public class SearchGameInfoActivity extends BaseActivity {
    @BindView(R.id.edt_search)
    EditText mEdtSearch;

    @BindView(R.id.img_word_clear)
    ImageView mImgClear;

    NavController mNavController;
    List<SearchHistoryModel> mHistoryList;
    ArrayList<String> mSuggestArrayList;
    private SearchHistoryProviderHelper mSearchHistoryProviderHelper;
    private String mSearchType;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        requestSearchHot();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    /**
     * 通过服务器获取热词
     */
    private void requestSearchHot() {
        getApiHelper().appGetOrderWords("", data -> {
            mSuggestArrayList = data;
            switchSuggestFragment();
        });
    }

    @Override

    protected int setLayoutId() {
        return R.layout.activity_game_info_search;
    }

    @Override
    protected void initData() {
        mSearchHistoryProviderHelper = SearchHistoryProviderHelper.getInstance();
        mHistoryList = mSearchHistoryProviderHelper.getDbInfo(getContext());
    }


    @Override
    protected void initView() {
        mEdtSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String content = s.toString();
                int state = View.GONE;
                if (!TextUtils.isEmpty(content)) {
                    state = View.VISIBLE;
                    switchWordFragment(content);
                } else {
                    switchSuggestFragment();
                }
                dealImgClearState(state);
            }
        });
        mEdtSearch.setOnEditorActionListener((v, actionId, event) -> {
            String content = v.getText().toString().trim();
            if (!TextUtils.isEmpty(content)) {
                switchResultFragment(content);
            }
            IMEUtil.hideInputMethod(SearchGameInfoActivity.this);
            return true;
        });
        mEdtSearch.setOnTouchListener((v, event) -> {
            if (MotionEvent.ACTION_UP == event.getAction()) {
                String content = mEdtSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(content)) {
                    switchWordFragment(content);
                }
            }
            return false;
        });
        Bundle bundle = getIntent().getExtras();
        if (null != bundle) {
            mEdtSearch.setHint(bundle.getString(KEY_SEARCH));
            mSearchType = bundle.getString(KEY_TYPE);
        }
        mEdtSearch.requestFocus();
        IMEUtil.showInputMethod(this, mEdtSearch);
        mNavController = Navigation.findNavController(this, R.id.nav_host_fragment);
    }

    /**
     * 处理删除键是否隐藏
     *
     * @param result
     */
    private void dealImgClearState(int result) {
        int state = mImgClear.getVisibility();
        if (state != result) {
            mImgClear.setVisibility(result);
        }
    }

    private void switchFragment(int id, Bundle bundle) {
        int current = mNavController.getCurrentDestination().getId();
        if (id != R.id.nav_search_suggest) {
            if (current != id) {
                mNavController.popBackStack();
                mNavController.navigate(id);
            }
        } else {
            mNavController.popBackStack();
            mNavController.navigate(id, bundle);
        }
    }

    @OnClick({R.id.img_word_clear, R.id.iv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.img_word_clear:
                if (null != mEdtSearch) {
                    mEdtSearch.setText("");
                }
                IMEUtil.hideInputMethod(SearchGameInfoActivity.this);
                switchSuggestFragment();
                break;
            case R.id.iv_back:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 接收消息
     *
     * @param msgDispatcher
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiveEvent(MsgDispatcher msgDispatcher) {
        SearchFragment searchFragment = msgDispatcher.getWhich();
        String content = msgDispatcher.getWordMsgEvent().getMsg();
        LogUtil.log("receiveEvent which = " + searchFragment.ordinal() + ",content = " + content);
        if (SearchFragment.WORD == searchFragment) {
            mEdtSearch.setText(content);
            Editable text = mEdtSearch.getText();
            Selection.setSelection(text, text.length());
            mEdtSearch.requestFocus();
            IMEUtil.showInputMethod(this, mEdtSearch);
        } else if (SearchFragment.RESULT == searchFragment) {
            mEdtSearch.setText(content);
            Editable text = mEdtSearch.getText();
            Selection.setSelection(text, text.length());
            IMEUtil.hideInputMethod(this);
            switchResultFragment(content);
        } else {
            insertDb(content);
        }
    }

    /**
     * 切换为搜索结果
     *
     * @param content
     */
    private void switchResultFragment(String content) {
        LogUtil.log("switchResultFragment content = " + content);
        switchFragment(R.id.nav_search_result, null);
        EventBus.getDefault().post(new GameInfoResultMsgEvent(content, mSearchType));
    }

    /**
     * 默认搜索界面
     */
    private void switchSuggestFragment() {
        Bundle bundle = new Bundle();
        if (null != mSuggestArrayList) {
            bundle.putStringArrayList(EXTRA_KEY_SEARCH_SUGGEST, mSuggestArrayList);
            bundle.putString(KEY_SEARCH, mSearchType);
        }
        switchFragment(R.id.nav_search_suggest, bundle);
    }

    /**
     * 切换为热词界面
     *
     * @param content
     */
    private void switchWordFragment(String content) {
        switchFragment(R.id.nav_search_wold, null);
        EventBus.getDefault().post(new WordMsgEvent(content, mSearchType));
    }

    /**
     * 插入数据库
     *
     * @param content
     */
    private void insertDb(String content) {
        int size = mHistoryList.size();
        int historySize = getResources().getInteger(R.integer.history_max_num);
        if (size == historySize) {
            mSearchHistoryProviderHelper.deleteOneDb(getContext(), mHistoryList.get(size - 1).getId());
        }
        List<SearchHistoryModel> models = new ArrayList<>();
        SearchHistoryModel model = new SearchHistoryModel();
        model.setContent(content);
        models.add(model);
        mSearchHistoryProviderHelper.insertDb(getContext().getContentResolver(), models);
    }
}
